import os
import pandas as pd
from search_baidu import get_baike_summary
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows

search_name = "文物保护单位名称"
summary_name = "简介内容"
target_col_idx = 11


# 依次读取文件夹下所有excel文件的每一行
def read_all_excel_rows(input_directory, output_directory):
    # 检查目录是否存在
    if not os.path.exists(input_directory):
        print("目录不存在")
        return

    # 遍历目录下所有文件
    for filename in os.listdir(input_directory):
        if filename.endswith(".xlsx"):
            file_path = os.path.join(input_directory, filename)
            try:
                # 读取原始 Excel 文件（保留合并信息）
                wb = load_workbook(file_path)
                ws = wb.active
                # 将工作表数据转换为 DataFrame（用于方便处理）
                df = pd.DataFrame(ws.values)
                # 设置列名为第二行
                df.columns = df.iloc[1]
                df = df[2:]
                df.insert(loc=min(target_col_idx, len(df.columns)), column=summary_name, value='')

                # 遍历 DataFrame 处理数据
                for idx, row in df.iterrows():
                    if pd.notna(row[search_name]):
                        df.at[idx + 1, summary_name] = get_baike_summary(str(row[search_name]))

                # 将处理后的数据写回原工作表
                for r_idx, row in enumerate(dataframe_to_rows(df, index=False, header=True), 1):
                    for c_idx, value in enumerate(row, 1):
                        if c_idx == df.columns.get_loc(summary_name) + 1:  # 只更新新列
                            if ws.cell(row=r_idx, column=c_idx).coordinate in ws.merged_cells:
                                # 如果是合并区域内的子单元格，跳过修改
                                continue
                            else:
                                ws.cell(row=r_idx, column=c_idx, value=value)

                wb.save(os.path.join(output_directory, filename))

            except Exception as e:
                print(e)
                continue
